package org.hank.compose_yyzs.ui.screen

import androidx.activity.compose.BackHandler
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.Divider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import com.orhanobut.logger.Logger
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import com.ramcosta.composedestinations.result.ResultBackNavigator
import com.ramcosta.composedestinations.spec.DestinationStyle
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import org.hank.compose_yyzs.R
import org.hank.compose_yyzs.bean.ProjectTreeNode
import org.hank.compose_yyzs.ui.navigation.style.SlideAnimatePopStyle
import org.hank.compose_yyzs.ui.theme.AppTheme
import org.hank.compose_yyzs.ui.theme.cyan4
import org.hank.compose_yyzs.ui.widget.EmptyCompose
import org.hank.compose_yyzs.utils.getString
import org.hank.compose_yyzs.utils.toJson
import org.hank.compose_yyzs.viewmodel.SearchViewModel

//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 *@auth: Hank
 *邮箱: cs16xiaoc1@163.com
 *创建时间: 2023/11/10 9:36
 *描述:
 */
@Composable
@Destination(style = SlideAnimatePopStyle::class)
fun SearchScreen(navigation: DestinationsNavigator, resultNavigator: ResultBackNavigator<String>) {
    var viewModel: SearchViewModel = hiltViewModel()
    var projectTree = viewModel.projectList.collectAsStateWithLifecycle()
    var searchText = viewModel.searchText.collectAsStateWithLifecycle()
    var lifecycleOwner = LocalLifecycleOwner.current
    var scope = rememberCoroutineScope()
    var focusManager = LocalFocusManager.current

    DisposableEffect(lifecycleOwner) {
        val observer = LifecycleEventObserver { _, event ->
            if (event == Lifecycle.Event.ON_CREATE) {
                viewModel.getProjectTree()
            }
        }
        lifecycleOwner.lifecycle.addObserver(observer)
        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(color = AppTheme.colors.mainColor)
            .clickable(onClick = {
                focusManager.clearFocus()
            }, indication = null, interactionSource = remember { MutableInteractionSource() })
    ) {
        Box(modifier = Modifier.fillMaxWidth()) {
            Text(
                text = "选择项目",
                style = MaterialTheme.typography.titleLarge,
                modifier = Modifier.align(
                    Alignment.Center
                )
            )
            Image(
                painter = painterResource(id = R.mipmap.ic_return_black),
                contentDescription = "",
                modifier = Modifier
                    .align(
                        Alignment.CenterStart
                    )
                    .clickable(
                        onClick = {
                            navigation.popBackStack()
                        },
                        indication = null,
                        interactionSource = remember { MutableInteractionSource() })
                    .padding(16.dp)
            )
        }
        Spacer(modifier = Modifier.height(8.dp))
        Divider()

        Box(
            modifier = Modifier
                .padding(16.dp)
                .height(IntrinsicSize.Min)
        ) {
            Surface(
                shape = MaterialTheme.shapes.large,
                modifier = Modifier
                    .wrapContentHeight()
                    .fillMaxWidth()
            ) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .background(color = AppTheme.colors.secondBtnBg)
                        .padding(8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Image(
                        painter = painterResource(id = R.mipmap.ic_search),
                        contentDescription = "",
                        modifier = Modifier.padding(start = 16.dp)
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    BasicTextField(
                        value = searchText.value,
                        singleLine = true,
                        onValueChange = {
                            scope.launch {
                                viewModel.searchText.emit(it)
                                //动态搜索
                                viewModel.filterData(it)
                            }
                        },
                        modifier = Modifier
                            .onFocusChanged {
                                scope.launch { viewModel.searchFocs.emit(it.hasFocus) }
                            },
                        keyboardOptions = KeyboardOptions.Default.copy(
                            keyboardType = KeyboardType.Text
                        ),
                        textStyle = MaterialTheme.typography.bodyLarge.copy(),
                        decorationBox = {
                            Box(
                                modifier = Modifier
                                    .fillMaxSize()
                                    .padding(4.dp)
                            ) {
                                if (searchText.value.isEmpty() && !viewModel.searchFocs.collectAsStateWithLifecycle().value) {
                                    Text(
                                        text = getString(resourceId = R.string.search_edit_hint),
                                        style = MaterialTheme.typography.bodyLarge.copy(color = AppTheme.colors.textSecondary)
                                    )
                                } else
                                    it.invoke()
                            }
                        }
                    )
                }
            }
        }


        if (projectTree.value.size > 0) {
            Divider(color = AppTheme.colors.divider)
            LazyColumn(modifier = Modifier.animateContentSize()) {
                items(items = projectTree.value) { item ->
                        ProjectTreeItemCompose(projectTreeNode = item) {
                            it.parent = null
                            resultNavigator.setResult(it.toJson())
                            navigation.popBackStack()
                        }
                }
            }
        } else {
            EmptyCompose()
        }
    }

}

@Composable
fun ProjectTreeItemCompose(
    modifier: Modifier = Modifier,
    projectTreeNode: ProjectTreeNode,
    onProjectClick: (ProjectTreeNode) -> Unit
) {
    var expand = remember { mutableStateOf(projectTreeNode.isExpand) }
    var animateRotate = animateFloatAsState(
        targetValue = if (expand.value) 180f else 0f,
        label = ""
    )
    LaunchedEffect(projectTreeNode) {
        expand.value = projectTreeNode.isExpand
    }

    Column(modifier = modifier) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
                .clickable(onClick = {
                    if (projectTreeNode.children.isNullOrEmpty()) {
                        onProjectClick.invoke(projectTreeNode)
                    } else {
                        expand.value = !expand.value
                    }
                }, indication = null, interactionSource = remember { MutableInteractionSource() })
        ) {
            Text(text = projectTreeNode.name, modifier = Modifier.weight(1f))
            if (!projectTreeNode.children.isNullOrEmpty() && projectTreeNode.children?.size != 0)
                Image(
                    painter = painterResource(id = R.mipmap.ic_packup_grey),
                    contentDescription = "",
                    modifier = Modifier.rotate(animateRotate.value)
                )
        }
        Divider(color = AppTheme.colors.divider)
        if (expand.value) {
            projectTreeNode.children?.forEach {
                ProjectTreeItemCompose(
                    modifier = Modifier.padding(start = 16.dp),
                    projectTreeNode = it,
                    onProjectClick = onProjectClick
                )
            }
        }
    }
}